import filterData from '@/common/filterData';
import mergeData from '@/common/mergeData';
import formatter from '@/common/formatter';
import department from '@/common/getDepartment';

const { department1, department2 } = department;

const r_g_Obj = department1.reduce((p, c, i) => {
	p[c] = department2[i].join(',');
	return p;
}, {})

const base = { title: '开通总体情况' };
const dataset = {
	source: [
		[
			'日期',
			'2022开通派单',
			'2023开通派单',
			'2024开通派单',
			'2022开通归档',
			'2023开通归档',
			'2024开通归档',
		],
		['2023年12月15日', 337, 376, 429, 444, 476, 364],
		['2023年12月16日', 364, 346, 492, 432, 484, 300],
	],
};

function getChartData(
	[dataPool1, dataPool2],
	condition,
	mergeDepartment = ['全市'],
	date
) {
	const collections = [
		NLObj.collections.pYear_kd.name,
		NLObj.collections.tYear_kd.name,
	];
	const fields = [
		'xp',
		'gd',
		'zt',
		// 'ztgdb'
	];
	const sheetHeader = [
		'新派',
		'归档',
		'在途',
		//  '在途归档比'
	];

	let _condition = ['茂南', '电白', '高州', '化州', '信宜'];
	if (condition && condition.length) {
		let condition2 = [...condition[1]]
		condition[0].map((i) => {
			let _g = r_g_Obj[i];
			condition2 = condition2.filter(i => _g.indexOf(i) < 0);
		})
		_condition = [...condition[0],...condition2]
	}

	const fieldSheet = collections.map((coll) => {
		const year = coll.match(/20\d\d/)[0];
		return fields.map((field, findex) => {
			const sheet = [['日期', year + sheetHeader[findex]]];
			const map = new Map();
			dataPool2[coll].forEach((row) => {
				let match = true;
				if (_condition && _condition.length) {
					match =
						(row.region && _condition.includes(row.region)) ||
						(row.grid && _condition.includes(row.grid));
				}
				if (match) {
					if (!map.has(row.date)) {
						map.set(row.date, +row[field]);
					} else {
						map.set(row.date, map.get(row.date) + (+row[field]));
					}
				}
			});
			let temp = [...map.keys()].sort((a, b) => a - b);
			temp.forEach((date) => {
				sheet.push([formatter.solarLunarDate(date), map.get(date)]);
			});
			return sheet;
		});
	});

	let orderData = [];
	for (let index = 0; index < fields.length; index++) {
		orderData.push(fieldSheet[0][index]);
		orderData.push(fieldSheet[1][index]);
		// orderData.push(fieldSheet[2][index])
	}

	["kuandai_huidanlv@回单率", "kuandai_zaituguidangbi@在途归档比"].forEach((collection) => {
		let [coll, title] = collection.split('@');
		let zhibiaoData = dataPool2[coll]
			.slice(1)
			.sort((a, b) => a['日期'] - b['日期']);

		let thisYear_zhibiaoData = zhibiaoData.filter((i) =>
			NLObj.thisYearDays.includes(i['日期'])
		);
		thisYear_zhibiaoData = [['日期', `${NLObj.thisYear}${title}`]].concat(
			thisYear_zhibiaoData.map((row, index) => {
				let v =
					mergeDepartment.reduce((p, d) => row[d] + p, 0) /
					mergeDepartment.length;
				return [formatter.solarLunarDate(row['日期']), v];
			})
		);

		let prevYear_zhibiaoData = zhibiaoData.filter((i) =>
			NLObj.prevYearDays.includes(i['日期'])
		);

		prevYear_zhibiaoData = [['日期', `${NLObj.prevYear}${title}`]].concat(
			prevYear_zhibiaoData.map((row, index) => {
				let v =
					mergeDepartment.reduce((p, d) => row[d] + p, 0) /
					mergeDepartment.length;
				return [formatter.solarLunarDate(row['日期']), v];
			})
		);


		orderData.push(prevYear_zhibiaoData);
		orderData.push(thisYear_zhibiaoData);
	})


	// 补充 因为闰年 导致的【冬月三十】和【腊月三十】缺失
	orderData = orderData.map((item) => {
		// 如果大于9 小于 40 则说明过了冬月，未到腊月三十
		if (item.length > 9 && item.length < 40) {
			let dongYue30Index = item.findIndex((i) => i[0] === '冬月三十');
			if (dongYue30Index < 0) {
				let dony29Index = item.findIndex((i) => i[0] === '冬月廿九');
				dony29Index >= 0 && item.splice(dony29Index + 1, 0, ['冬月三十', '']);
			}
		} else if (item.length >= 40) {
			// 如果大于等于于 40 则说明过了冬月，到腊月三十
			let dongYue30Index = item.findIndex((i) => i[0] === '冬月三十');
			if (dongYue30Index < 0) {
				let dony29Index = item.findIndex((i) => i[0] === '冬月廿九');
				dony29Index >= 0 && item.splice(dony29Index + 1, 0, ['冬月三十', '']);
			}

			let laYue30Index = item.findIndex((i) => i[0] === '腊月三十');
			if (laYue30Index < 0) {
				let lay29Index = item.findIndex((i) => i[0] === '腊月廿九');
				lay29Index >= 0 && item.splice(lay29Index + 1, 0, ['腊月三十', '']);
			}
		}
		let newItem = item.map((i) => [i[0], i[1] || '']);
		return newItem;
	});
	const data = mergeData.mergeSheets(orderData);

	this.dataset.source = data;

	if (data.length > 7) {
		this.dataZoom[0].show = true;
	}
}

const seriesTemplate = [
	[
		// 'bar',
		// 'bar',
		// 'bar',
		'bar',
		'bar',
		'bar',
		'bar',
		'line',
		'line',
	],
	[
		// 'line',
		'line',
		'line',
	],
	[
		'line',
		'line',
	],
];

// ======更新内容↑========

const series = seriesTemplate.flatMap((arr, index) =>
	arr.map((type) => ({ type, yAxisIndex: index }))
);

const source = dataset.source;
// const dataZoomStart = source.length > 7 ? source.slice(-7)[0][0] : source[1][0];

export default {
	title: {
		text: base.title,
		left: 'center',
	},
	legend: {
		type: 'scroll',
		top: 30,
	},
	tooltip: {
		trigger: window.isMobile ? 'item' : 'axis',
		axisPointer: {
			type: 'cross',
			crossStyle: {
				color: '#999',
			},
		},
		formatter: (params) => {
			if (window.isMobile) {
				const value =
					params.value[params.dimensionNames.indexOf(params.seriesName)];
				let tip = `<div class="space-y-1"><div class='font-bold'>${params.name}</div>`;
				tip += `<div class='flex justify-between space-x-6 p-0'>
        <span>${params.marker + params.seriesName}</span>
        <span class="font-bold">${value ? formatter.valueToText(value) : '-'
					}</span>
        </div>`;
				tip += '</div>';
				return tip;
			} else {
				let tip = `<div class="space-y-1"><div class='font-bold'>${params[0].name}</div>`;
				params.forEach((item, index) => {
					const value =
						item.value[item.dimensionNames.indexOf(item.seriesName)];
					const r = item.seriesName.endsWith('回单率');
					tip += `<div class='flex justify-between space-x-6 p-0'>
        <span>${item.marker + item.seriesName}</span>
        <span class="font-bold">${value ? formatter.valueToText(value, r, r ? 2 : void 0) : '-'
						}</span>
        </div>`;
				});
				tip += '</div>';
				return tip;
			}
		},
	},
	grid: {
		width: '96%',
		height: '80%',
		left: '2%',
		right: '2%',
		top: '16%',
		bottom: '2%',
		containLabel: true,
	},
	dataset,
	dataZoom: [{ show: false }],
	xAxis: {
		type: 'category',
		axisPointer: {
			type: 'shadow',
		},
	},
	yAxis: [
		{
			type: 'value',
			name: '',
		},
		{
			type: 'value',
			name: '',
			offset: 20,
			axisLabel: {
				formatter: (value) => formatter.valueToText(value, true),
			},
		},
		{
			type: 'value',
			name: '',
			axisLabel: {
				formatter: (value) => formatter.valueToText(value, false, 1),
			},
		},
	],
	series,
	getChartData,
};
